#!/usr/bin/python
# sample main program that acts as image distribution server

import sys
import time
import ImgDist

_start_time = time.time()


def print_time(*pos):
    "prints the current time since start plus arguments"
    act_time = time.time() - _start_time
    print "%7.3f:" % act_time, " ".join(map(str, pos))

def print_img_accept(img):
    "print len of accepted image"
    print_time("accepted image", len(img))

def print_img_dist(img):
    "print len of distributed image"
    print_time("distributed image", len(img))


def main(ImgDistClass, server, inport, outport):
    print "Testing ImgDist via", server
    # Note, two different servers on two different ports 
    # avoid blockage if too many read requests arrive,
    # although that shouldn't happen.
    img_dist_in = ImgDistClass(port=inport) 
    img_dist_out = None
    if outport:
        img_dist_out = ImgDistClass(port=outport)
    in_observers = img_dist_in.observers
    if img_dist_out:
        out_observers = img_dist_out.observers
    if "-l" in sys.argv or "-v" in sys.argv: # be verbose/log
        in_observers.add(ImgDist.LOG, print_time)
        if img_dist_out:
            out_observers.add(ImgDist.LOG, print_time)
    if "-a" in sys.argv or "-v" in sys.argv: # log accept
        in_observers.add(ImgDist.ACCEPT, print_img_accept)
    if "-d" in sys.argv or "-v" in sys.argv: # log distribute
        if img_dist_out:
            out_observers.add(ImgDist.DIST, print_img_dist)
        else:
            img_dist_in.add(ImgDist.DIST, print_img_dist)
    sleep_time = 60 # run for a minute
    if "-i" in sys.argv:
        sleep_time = 2**30  # run rather long (indefinite)
    try:
        img_dist_in.start()
        if img_dist_out:
            img_dist_out.start()
        time.sleep(sleep_time)
    except Exception, data: # Ctrl-C
        print data
    except:
        print "caught an exception"
    img_dist_in.stop() # stop anyway
    if img_dist_out:
        img_dist_out.stop() # stop anyway
    
    
if __name__ == '__main__':
    print sys.argv[0], " -s to use sockets, -a/-d to log accepted/distributed images, -v to be verbose"
    if "-s" in sys.argv: # socket
        main(ImgDist.ImgDistSocket, "socket",
             ImgDist.SOCKET_PORT, None)
    else: # http default
        main(ImgDist.ImgDistHTTP, "HTTP",
             ImgDist.HTTP_INPORT, ImgDist.HTTP_OUTPORT)
